package com.recipes.meg;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class Edit extends Activity {
	// Initialize variables to hold sqlite database and database helper
	SQLiteDatabase db;
	DatabaseHelper db_helper;
	
	// Initialize int to hold id value
	int id;
	
	// Initialize array to hold ingredient inputs
	ArrayList<EditText> ingredients = new ArrayList<EditText>();
	
	// Initialize array to hold rows
	ArrayList<TableRow> rows = new ArrayList<TableRow>();
	
	// Initialize array to hold delete buttons
	ArrayList<Button> deletes = new ArrayList<Button>();
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);
        
        // Initialize new database helper variable
        db_helper = new DatabaseHelper(this);
        
        // Get id from calling activity
        id = this.getIntent().getIntExtra("id", 1);
        
        // Open database for reading
        db = db_helper.getWritableDatabase();
        
        // Get the name of this recipe
        String name = db_helper.getName(db, id);
        
        // Get number of ingredients for this recipe
        int num_ing = db_helper.getNumIng(db, id);
        
        // Get names of ingredients for this recipe
        ArrayList<String> ing_names = db_helper.getIng(db, id);
        
        // Close the database
        db.close();
        
        // Get EditText box to hold name
        EditText name_in = (EditText) findViewById(R.id.name_in);
        
        // Set the starting text for this text input box to be the current name of this recipe
        name_in.setText(name);
        
        // Get table layout to put ingredients in
        final TableLayout ing_layout = (TableLayout) findViewById(R.id.ing_table);
        
        // Iterate for each ingredient
        for(int i = 0; i < num_ing; i++){
        	// Create a new row for the table
        	final TableRow temp_row = new TableRow(this);
        	
        	// Create EditText field
        	EditText temp_in = new EditText(this);

        	// Set this EditText field to capitalize the first letter of each word and use auto complete
        	temp_in.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
        
        	// Set the starting text of this field to be the current name of this ingredient
        	temp_in.setText(ing_names.get(i));
        	
        	// Declare the parameters to be used for this input box
        	TableRow.LayoutParams temp_params2 = new TableRow.LayoutParams(
        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        	
        	// Set the left right and bottom margins of this input box to be 5
        	temp_params2.setMargins(5, 0, 5, 5);
        	
        	// Set the weight of this input box to be 0.7
        	temp_params2.weight = (float) 0.7;
        	
        	// Add temp_in to the row
        	temp_row.addView(temp_in, temp_params2);
        	
        	// Add temp_in to ingredients array
        	ingredients.add(temp_in);
        	
        	// Create a button
        	final Button temp_delete = new Button(this);
        	
        	// Set the text of this button to be Delete
        	temp_delete.setText("Delete");
        	
        	// Declare the parameters to be used for this button
        	TableRow.LayoutParams temp_params3 = new TableRow.LayoutParams(
        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        	
        	// Set the right and bottom margins of this button to be 5
        	temp_params3.setMargins(0, 0, 5, 5);
        	
        	// Set the weight of this button to be 0.3
        	temp_params3.weight = (float) 0.3;
        	
        	// Set the onClickListener for temp_delete
        	temp_delete.setOnClickListener(new View.OnClickListener() {
				// Override onClick function
				@Override
				public void onClick(View v) {
					// Initialize row_id to -1
					int row_id = -1;
					
					// Iterate through deletes array
					for(int i = 0; i < deletes.size(); i++){
						// Check if temp_delete is this delete
						if(temp_delete.equals(deletes.get(i))){
							// If so then set this row id to be i
							row_id = i;
						}
					}
					
					// Make sure row_id is not negative and that this isnt the only row
					if(row_id >= 0 && deletes.size() > 1){		
						// Remove this rows input box from the ingredients array
						ingredients.remove(row_id);
					
						// Remove this rows delete button from the deletes array
						deletes.remove(row_id);
					
						// Remove this row from the table layout
						ing_layout.removeView(temp_row);
					
						// Remove this row from the rows array
						rows.remove(row_id);
					}
				}
			});
        	
        	// Add temp_delete to the row
        	temp_row.addView(temp_delete);
        	
        	// Add temp_delete to the deletes array
        	deletes.add(temp_delete);
        	
        	// Add temp_row to the table layout
        	ing_layout.addView(temp_row, new TableLayout.LayoutParams(
        			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        	
        	// Add temp_row to the rows array
        	rows.add(temp_row);
        }
        
        // Initialize button to add ingredients
        Button add = (Button) findViewById(R.id.add_ing);
        
        // Set onClickListener for add
        add.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Create a new row for the table
	        	final TableRow temp_row = new TableRow(getApplicationContext());
	        	
	        	// Create EditText field
	        	EditText temp_in = new EditText(getApplicationContext());

	        	// Set this EditText field to capitalize the first letter of each word and use auto complete
	        	temp_in.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
	            		
	        	// Declare the parameters to be used for this input box
	        	TableRow.LayoutParams temp_params2 = new TableRow.LayoutParams(
	        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        	
	        	// Set the left, right and bottom margins of this input box to be 5
	        	temp_params2.setMargins(5, 0, 5, 5);
	        	
	        	// Set the weight of this input box to be 0.7
	        	temp_params2.weight = (float) 0.7;
	        	
	        	// Add temp_in to the row
	        	temp_row.addView(temp_in, temp_params2);
	        	
	        	// Add temp_in to ingredients array
	        	ingredients.add(temp_in);

	        	// Create a button
	        	final Button temp_delete = new Button(getApplicationContext());
	        	
	        	// Set the text of this button to be Delete
	        	temp_delete.setText("Delete");
	        	
	        	// Declare the parameters to be used for this button
	        	TableRow.LayoutParams temp_params3 = new TableRow.LayoutParams(
	        			LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        	
	        	// Set the right and buttom margins of this button to be 5
	        	temp_params3.setMargins(0, 0, 5, 5);
	        	
	        	// Set the weight of this button to be 0.3
	        	temp_params3.weight = (float) 0.3;
	        	
	        	// Add temp_delete to the row
	        	temp_row.addView(temp_delete);
	        	
	        	// Add temp_delete to the deletes array
	        	deletes.add(temp_delete);
	        	    	
	        	// Add temp_row to the table layout
	        	ing_layout.addView(temp_row, new TableLayout.LayoutParams(
	        			LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
	        	
	        	// Add temp_row to the rows array
	        	rows.add(temp_row);

	        	// Set the onClickListener for temp_delete
	        	temp_delete.setOnClickListener(new View.OnClickListener() {
					// Override onClick function
					@Override
					public void onClick(View v) {
						// Initialize row_id to -1
						int row_id = -1;
						
						// Iterate through deletes array
						for(int i = 0; i < deletes.size(); i++){
							// Check if temp_delete is this delete
							if(temp_delete.equals(deletes.get(i))){
								// If so then set this row id to be i
								row_id = i;
							}
						}
						
						// Make sure row_id is not negative
						if(row_id >= 0){		
							// Remove this rows input box from the ingredients array
							ingredients.remove(row_id);
						
							// Remove this rows delete button from the deletes array
							deletes.remove(row_id);
						
							// Remove this row from the table layout
							ing_layout.removeView(temp_row);
						
							// Remove this row from the rows array
							rows.remove(row_id);
						}
					}
				});
			}
		});
        
        // Initialize button to move to next screen and save current results
        Button next = (Button) findViewById(R.id.next);
        
        // Set onClickListener for next
        next.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {
				// Instantiate EditText field for name
				EditText name_in = (EditText) findViewById(R.id.name_in);
				
				// Get contents of name_in
				String name = name_in.getText().toString();
				
				// Check if name is not blank
				if(name.equalsIgnoreCase("")){
					// If it is then give an error message and return prematurely
					Toast.makeText(getApplicationContext(), "Recipe must have a name", Toast.LENGTH_SHORT).show();
					return;
				}
				
				// Open database for reading
				db = db_helper.getWritableDatabase();
				
				// Call function to check if name is a duplicate of other recipes
				int result = db_helper.duplicateName(db, name, id);
				
				// Close database
				db.close();
				
				// Check if result was not 0
				if(result != 0){
					// If so then check if result was positive
					if(result > 0){
						// If it is then give an error message
						Toast.makeText(getApplicationContext(), "Recipe must have a unique name", Toast.LENGTH_SHORT).show();
					}
					
					// Return prematurely
					return;
				}

				// Initialize a hashtable to store contents of ingredients input boxes
				Hashtable<String, Integer> ing_hashes = new Hashtable();
				
				// Initialize arraylist to hold input names of ingredients
				ArrayList<String> names = new ArrayList<String>();
				
				// Iterate through ingredients array
				for(int i = 0; i < ingredients.size(); i++){
					// Get the contents of this ingredients input box
					String ing = ingredients.get(i).getText().toString();

					// Make sure this input is not blank
					if(ing.equalsIgnoreCase("")){
						// If it is then give an error message and return prematurely
						Toast.makeText(getApplicationContext(), "Recipe cannot have blank ingredients", Toast.LENGTH_SHORT).show();
						return;
					}
					
					// Check if the all lowercase version of ing has already been used 
						// as a key for ing_hashes
					Integer exists = 0;
					exists = ing_hashes.get(ing.toLowerCase());
					
					// Check if this hash lookup returned non-null
					if(exists != null){
						// If so then give an error message and return prematurely
						Toast.makeText(getApplicationContext(), "Recipe must have unique ingredients", Toast.LENGTH_SHORT).show();
						return;
					}
					
					// Otherwise it did return null
					else{
						// If so then put a 1 into ing_hashes using the all lowercase version
							// of ing as its key
						ing_hashes.put(ing.toLowerCase(), 1);
					}
					
					// Put the text in this input box into the names array
					names.add(ing);
				}

				// Open database for reading and writing
				db = db_helper.getWritableDatabase();
				
				// Call function to update a recipe
				boolean updated = db_helper.update(db, id, name, names);
				
				// Close the database
				db.close();
				
				// Check if insertion failed
				if(!updated){
					// If this returned negative give an error message and return prematurely
					Toast.makeText(getApplicationContext(), "Recipe was not updated", Toast.LENGTH_SHORT).show();
					return;
				}
				
				// Initialize intent to start Edit2 activity
				Intent start_edit2 = new Intent(getApplicationContext(), Edit2.class);

				// Put id of new recipe into intent as an extra
				start_edit2.putExtra("id", id);
				
				// Start start_edit2 intent
				startActivity(start_edit2);

				// Upon return to this activity finish it
				finish();
			}
		});
    }
}
